<template>
  <div id="app">
    <meta name="referrer" content="no-referrer" />
    <table class="cart">
      <caption>
        购物车
      </caption>
      <tr>
        <th>全选 <input type="checkbox" v-model="state" /></th>
        <th>商品</th>
        <th>价格</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>
      </tr>

      <tr v-for="item in carts" :key="item.id">
        <td><input type="checkbox" v-model="item.isSelected" /></td>
        <td>
          <img class="cover" :src="item.productCover" alt="" />{{
            item.productName
          }}
        </td>
        <td>¥{{ item.productPrice }}</td>
        <td><input type="number" v-model="item.num" min="1" /></td>
        <td>{{ item.Subtotal }}</td>
        <td>
          <button @click="remove(index)">移除</button>
        </td>
      </tr>

      <tr>
        <td colspan="6" class="left">总价格: ¥{{ total }}</td>
      </tr>
    </table>
  </div>
</template>

<script setup>
import { ref, computed, watchEffect } from 'vue'
import axios from 'axios'
const carts = ref([])

axios.get('http://39.103.151.139:8000/cart').then((res) => {
  carts.value = res.data.map((item) => {
    return {
      isSelected: item.isSelected,
      productCover: item.productCover,
      productName: item.productName,
      productPrice: item.productPrice,
      num: 1,
      Subtotal: item.productPrice,
      op: '删除',
    }
  })
  console.log(carts.value)
  console.log(carts)
})
watchEffect(() => {
  carts.value.forEach((item) => {
    item.Subtotal = item.productPrice * item.num
  })
})
const state = computed({
  get: () => {
    return carts.value.every((item) => item.isSelected)
  },
  set: (val) => {
    carts.value.forEach((item) => {
      item.isSelected = val
    })
  },
})

const total = computed(() => {
  return carts.value
    .filter((item) => (item.isSelected = true))
    .reduce((pre, cur) => (pre += cur.productPrice * cur.num), 0)
    .toFixed(2)
})

function remove(index) {
  carts.value.splice(index, 1)
}
</script>

<style scoped>
/* reset重置 */
body {
  margin: 0;
  padding: 0;
}
/* common样式 */
table,
tr,
th,
td {
  border: 1px solid #ccc;
  border-spacing: 0;
  border-collapse: collapse;
}
#app .cart {
  margin: 20px auto;
  width: 1000px;
  font-size: 14px;
}
#app .cart caption {
  font-size: 16px;
  font-weight: 700;
}
#app .cart th {
  padding: 5px 15px;
  background-color: #f7f7f7;
  color: #666;
}
#app .cart td {
  padding: 5px 10px;
}
#app .cart .right {
  text-align: left;
}
#app .cart .cover {
  height: 100px;
  width: 80px;
}
</style>
